package org.itboys.ace.web;

import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.lang.StringUtils;
import org.itboys.ace.dto.ZTreeDto;
import org.itboys.admin.dto.AdminUserDTO;
import org.itboys.admin.entity.AdminOrg;
import org.itboys.admin.entity.AdminPost;
import org.itboys.admin.entity.AdminRole;
import org.itboys.admin.entity.AdminUser;
import org.itboys.admin.entity.AdminUserOrgPost;
import org.itboys.admin.entity.AdminUserRole;
import org.itboys.admin.service.AdminOrgService;
import org.itboys.admin.service.AdminPostService;
import org.itboys.admin.service.AdminRoleService;
import org.itboys.admin.service.AdminUserOrgPostService;
import org.itboys.admin.service.AdminUserService;
import org.itboys.admin.tools.AdminPermissionCheck;
import org.itboys.admin.tools.AdminSessionHolder;
import org.itboys.commons.CommonConstants;
import org.itboys.commons.utils.ajax.AjaxUtils;
import org.itboys.commons.utils.collection.CommonCollectionUtils;
import org.itboys.commons.utils.encryption.Digests;
import org.itboys.commons.utils.io.FileUtils;
import org.itboys.commons.utils.number.ToNumberUtils;
import org.itboys.framework.resource.ResourceHolder;
import org.itboys.framework.spring.controller.BaseController;
import org.itboys.mongodb.utils.page.AceJsonPageUtils;
import org.itboys.mongodb.utils.page.Page;
import org.itboys.mongodb.utils.query.AceUtils;
import org.itboys.mongodb.utils.query.QueryParamUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.google.common.collect.Lists;

/**
 * 用户管理
 * 
 * @author weisky
 *
 */
@RestController
@RequestMapping("/ace/admin/user")
public class AceAdminUserController extends BaseController {

	@Autowired
	private AdminUserService adminUserService;
	@Autowired
	private AdminRoleService adminRoleService;
	@Autowired
	private ResourceHolder resourceHolder;
	@Autowired
	private AdminOrgService adminOrgService;
	@Autowired
	private AdminUserOrgPostService adminUserOrgPostService;
	@Autowired
	private AdminPostService adminPostService;

	/**
	 * 点击用户管理跳转页面
	 * 
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping("/user-list")
	public ModelAndView listvm(HttpServletRequest request, HttpServletResponse response, Model model) {
		Map<String, Object> param = QueryParamUtils.builderQueryMap(request);
		List<AdminOrg> org = adminOrgService.list(param);
		List<AdminPost> post = adminPostService.list(param);
		model.addAttribute("post", post);
		model.addAttribute("org", org);
		return new ModelAndView("/ace/admin/user-list");
	}

	/**
	 * 分页查询管理用户
	 * 
	 * @return
	 */
	@RequestMapping("/list")
	public void list(HttpServletRequest request, HttpServletResponse response) {
		Map<String, Object> param = QueryParamUtils.builderQueryMap(request);
		if (null != param.get("username")) {
			param.put("username", AceUtils.getPattern(param.get("username")));
		}
		if (null != param.get("name")) {
			param.put("name", AceUtils.getPattern(param.get("name")));
		}
		if (null != param.get("mobi")) {
			param.put("mobi", AceUtils.getPattern(param.get("mobi")));
		}
		Page<AdminUser> page = adminUserService.pageQuery(param, request);
		List<AdminUser> userList = page.getData();
		if(!userList.isEmpty()) {
			for (AdminUser adminUser : userList) {
				AdminOrg adminOrg = adminOrgService.getById(adminUser.getOrgId());
				if (null != adminOrg) {
					adminUser.setOrgName(adminOrg.getName());//组织名称
				}
				AdminPost adminPost = adminPostService.getById(adminUser.getPostId());
				if (null != adminPost) {
					adminUser.setPostName(adminPost.getName());// 职务名称
				}
			}
		}
		AceJsonPageUtils.renderJsonPage(page.getTotal(), page.getData(), response);
	}

	/**
	 * 异步获取单个用户对象
	 * 
	 * @param id
	 * @param response
	 */
	@RequestMapping("/getUser/{id}")
	public void getUser(@PathVariable("id") Long id, HttpServletResponse response) {
		AdminUserDTO user = adminUserService.getUserById(id);
		AjaxUtils.renderJson(response, user);
	}

	/**
	 * 个人资料保存
	 * 
	 * @param user
	 * @param request
	 * @param response
	 * @param logos
	 */
	@RequestMapping("/saveUserInfo")
	@AdminPermissionCheck("saveUserInfo:save")
	public void saveUserInfo(
			@ModelAttribute AdminUser user,
			HttpServletRequest request,
			HttpServletResponse response,
			@RequestParam(value = "logos", required = false) CommonsMultipartFile logos) {
		try {
			if (logos != null && !logos.isEmpty()) {
				FileItem item = logos.getFileItem();
				String filePath = FileUtils.saveFile(item.getInputStream(), resourceHolder.getStringValue("fileUploadPath"), item.getName(), item.getContentType());
				user.setBigLogo(filePath);
			}
			adminUserService.doUpdateUserInfo(user);
			AjaxUtils.renderText(response, CommonConstants.SUCCESS);
		} catch (Exception e) {
			logger.error("save admin userInfo error", e);
			e.printStackTrace();
			AjaxUtils.renderText(response, CommonConstants.FAIL);
		}
	}

	/**
	 * 密码修改
	 * 
	 * @param response
	 * @param password
	 * @param newPassword
	 * @param rePassword
	 */
	@RequestMapping("/savePass")
	@AdminPermissionCheck("adminUser:savePass")
	public void savePass(
			HttpServletResponse response,
			@RequestParam(value = "password", required = true) String password,
			@RequestParam(value = "newPassword", required = true) String newPassword,
			@RequestParam(value = "rePassword", required = true) String rePassword) {
		int flag = adminUserService.updatePassword(password, newPassword, rePassword);
		if (flag == -1) {
			AjaxUtils.renderText(response, CommonConstants.FAIL);
		} else if (flag == 1) {
			AjaxUtils.renderText(response, CommonConstants.SUCCESS);
		} else if (flag == 2) {
			AjaxUtils.renderText(response, CommonConstants.FAIL);
		}
	}

	/**
	 * 异步保存
	 */
	@RequestMapping("/save")
	@AdminPermissionCheck("adminUser:save")
	public void save(
			@ModelAttribute AdminUser user,
			HttpServletRequest request,
			HttpServletResponse response,
			//@RequestParam(value = "logos", required = false) MultipartFile[] logos
			@RequestParam(value = "logos", required = false) CommonsMultipartFile logos) {
		try {
//			if (logos != null) {
//				for (MultipartFile fileItem : logos) {
//					String fileName = fileItem.getOriginalFilename();
//					if (null != fileName && !"".equals(fileName)) {
//						String filePath = FileUtils.saveFile(fileItem.getInputStream(), resourceHolder.getStringValue("fileUploadPath"), fileItem.getOriginalFilename(), fileItem.getContentType());
//						user.setBigLogo(filePath);
//					}
//				}
//			}
			
			if (logos != null && !logos.isEmpty()) {
				FileItem item = logos.getFileItem();
				String filePath = FileUtils.saveFile(item.getInputStream(), resourceHolder.getStringValue("fileUploadPath"), item.getName(), item.getContentType());
				user.setBigLogo(filePath);
			}

			String userOrgPostIsManager = request.getParameter("userOrgPostIsManager");
			String userOrgPostId = request.getParameter("userOrgPostId");

			AdminUserOrgPost userOrgPost = new AdminUserOrgPost();
			userOrgPost.setOrgId(ToNumberUtils.getLongValue(user.getOrgId()));
			userOrgPost.setPostId(ToNumberUtils.getLongValue(user.getPostId()));
			userOrgPost.setIsManager(StringUtils.isBlank(userOrgPostIsManager) ? 0 : Integer.valueOf(userOrgPostIsManager));
			if (user.getId() != 0l) {
				userOrgPost.setId(StringUtils.isBlank(userOrgPostId) ? 0 : Long.valueOf(userOrgPostId));
			}

			userOrgPost.setOrgId(ToNumberUtils.getLongValue(user.getOrgId()));
			userOrgPost.setPostId(ToNumberUtils.getLongValue(user.getPostId()));
			userOrgPost.setIsManager(StringUtils.isBlank(userOrgPostIsManager) ? 0 : Integer.valueOf(userOrgPostIsManager));
			if (user.getId() != 0l) {
				userOrgPost.setId(StringUtils.isBlank(userOrgPostId) ? 0 : Long.valueOf(userOrgPostId));
			}

			AdminUserDTO dto = new AdminUserDTO();
			dto.setAdminUser(user);
			dto.setUserOrgPost(userOrgPost);
			if (user.getId() == 0l) {
				adminUserService.insert(dto);
			} else {
				adminUserService.doUpdate(dto);
			}
			AjaxUtils.renderText(response, CommonConstants.SUCCESS);
		} catch (Exception e) {
			logger.error("save admin user error", e);
			e.printStackTrace();
			AjaxUtils.renderText(response, CommonConstants.FAIL);
		}
	}

	/**
	 * 根据ID，获取角色
	 * 
	 * @param id
	 * @param response
	 */
	@RequestMapping("getUserRole/{id}")
	public void getUserRole(@PathVariable Long id, HttpServletResponse response) {
		List<AdminRole> roleList = adminRoleService.list();
		List<ZTreeDto> tree = Lists.newArrayListWithCapacity(roleList.size());
		List<Long> userRole = adminRoleService.getAdminRoleByUserIds(id);
		for (AdminRole roles : roleList) {
			ZTreeDto roleTree = new ZTreeDto();
			roleTree.setId(roles.getId());
			roleTree.setName(roles.getName());
			if (userRole.contains(roles.getId())) {
				roleTree.setChecked(true);
			}
			tree.add(roleTree);
		}
		AjaxUtils.renderJson(response, tree);
	}

	/**
	 * 设置用户角色
	 * 
	 * @param request
	 * @param response
	 */
	@RequestMapping("setUserRoles")
	@AdminPermissionCheck("AdminUser:setUserRoles")
	public void setUserRoles(HttpServletRequest request,
			HttpServletResponse response) {
		try {
			Long userId = Long.valueOf(request.getParameter("userId"));
			String str = request.getParameter("roleIds");
			List<Long> roleIds = CommonCollectionUtils.splictToLongList(str, ",");
			adminRoleService.insertUserRole(userId, roleIds);
			AjaxUtils.renderText(response, CommonConstants.SUCCESS);
		} catch (Exception e) {
			AjaxUtils.renderText(response, CommonConstants.FAIL);
		}
	}

	/**
	 * 异步删除
	 */
	@RequestMapping("/delete/{id}")
	@AdminPermissionCheck("AdminUser:delete")
	public void delete(@PathVariable("id") Long id, HttpServletResponse response) {
		try {
			adminUserService.delete(id);
			AjaxUtils.renderText(response, CommonConstants.SUCCESS);
		} catch (Exception e) {
			logger.error(" AdminUser delete error", e);
			AjaxUtils.renderText(response, CommonConstants.FAIL);
		}
	}
	
	/**
	 * 异步删除LOGO
	 */
	@RequestMapping("/deleteImage/{id}")
	@AdminPermissionCheck("deleteImage")
	public void deleteImage(@PathVariable("id") Long id, HttpServletResponse response) {
		try {
			AdminUser adminUser = adminUserService.getById(id);
			adminUser.setBigLogo("");
			adminUserService.update(adminUser);
			AjaxUtils.renderText(response, CommonConstants.SUCCESS);
		} catch (Exception e) {
			logger.error("AdminUser deleteImage error", e);
			AjaxUtils.renderText(response, CommonConstants.FAIL);
		}
	}

	@RequestMapping("/simpleUpdate")
	public void simpleSave(@ModelAttribute AdminUser AdminUser,
			HttpServletResponse response,
			@RequestParam("logos") MultipartFile logos) {
		try {
			if (logos != null && !logos.isEmpty()) {
				String filePath = FileUtils.saveFile(logos.getInputStream(), resourceHolder.getStringValue("fileUploadPath"), logos.getOriginalFilename(), logos.getContentType());
				AdminUser.setBigLogo(filePath);
			}
			if (AdminUser.getId() == 0l) {
				AdminUser.setPassword(Digests.md5(AdminUser.getPassword()));
				adminUserService.save(AdminUser);
				AdminOrg AdminOrg = adminOrgService.getById(AdminUser.getOrgId());
				AdminUserOrgPost AdminUserOrgPost = new AdminUserOrgPost();
				AdminUserOrgPost.setOrgId(AdminUser.getOrgId());
				AdminUserOrgPost.setPostId(0l);
				//AdminUserOrgPost.setDeptName(AdminOrg.getFullNamePath());
				AdminUserOrgPost.setUserId(AdminUser.getId());
				AdminUser.setPassword(Digests.md5(AdminUser.getPassword()));
				adminUserOrgPostService.save(AdminUserOrgPost);
				AdminUserRole userRole = new AdminUserRole();
				userRole.setUserId(AdminUser.getId());
				userRole.setType(1);
			} else {
				AdminUser user = adminUserService.getById(AdminUser.getId());
				AdminUser.setCr(user.getCr());
				AdminUser.setCt(user.getCt());
				AdminUser.setOrgId(user.getOrgId());
				AdminUser.setPostId(user.getPostId());
				AdminUser.setPassword(user.getPassword());
				AdminUser.setUr(AdminSessionHolder.getAdminUserId());
				AdminUser.setUt(System.currentTimeMillis());
				adminUserService.update(AdminUser);
			}

			AjaxUtils.renderText(response, CommonConstants.SUCCESS);
		} catch (Exception e) {
			logger.error("simpleSave Admin user error", e);
			AjaxUtils.renderText(response, CommonConstants.FAIL);
		}
	}

}
